import { takeEvery } from 'redux-saga';
import { put, call } from 'redux-saga/effects'
import { SAVE, SAVE_SUCCESS, SAVE_FAIL} from './constants'
import { ax_get,ax_post } from '../../utils/ax_agent'
import jscookie from 'js-cookie'

export default function* postSaga() {
  yield [
    saveGamePostEditor()
  ]
}

function* savePost(action) {
   try {

      const gotUser = yield call( ax_get,  '/api/user/me',
        { headers: {  'Authorization': 'Bearer ' + jscookie.get('app_user_token')  } }   );

      console.log("Saving user_id: " + gotUser.data._id)

      console.log("Saving title: " + action.payload.title)

      const result = yield call( ax_post,  '/api/gamePost', 
        {
          _creator : gotUser.data._id, 
          _comments : [], 
          type : "game", 
          title: action.payload.postTitle, 
          content: JSON.stringify(action.payload.draftjsRawObject)
        }, 
        )

      yield put({type: SAVE_SUCCESS, result: result.data})
   
   } catch (e) {

      yield put({type: SAVE_FAIL, message: e.message})

   }
}

function* saveGamePostEditor() {
  yield* takeEvery( SAVE, savePost)
}